package cn.tedu.recruitmentwebsite.common.controller;

import cn.tedu.recruitmentwebsite.common.service.SmsService;
import cn.tedu.recruitmentwebsite.common.service.VerificationCodeService;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @PostMapping("/sendVerificationCode")
    public String sendVerificationCode( String phoneNumber) {
        log.info("发送验证码，手机号：{}", phoneNumber);
        String code = String.format("%04d", (int) (Math.random() * 10000)); // 生成4位随机验证码
        try {
            SendSmsResponse response = smsService.sendSms(phoneNumber, code);
            if (response.getCode() != null && response.getCode().equals("OK")) {
                verificationCodeService.saveVerificationCode(phoneNumber, code);
                return "验证码发送成功";
            } else {
                return "验证码发送失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "验证码发送失败";
        }
    }
}
